package com.thinkfit.jy.presenter;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.common.lib.bean.UserBean;
import com.common.lib.constant.Constants;
import com.common.lib.manager.DataManager;
import com.common.lib.mvp.BasePresenter;
import com.common.lib.network.HttpListener;
import com.common.lib.network.HttpMethods;
import com.common.lib.network.HttpObserver;
import com.common.lib.network.OkHttpManager;
import com.common.lib.utils.LogUtil;
import com.thinkfit.jy.contract.LoginContract;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {


    public LoginPresenter(@NotNull LoginContract.View rootView) {
        super(rootView);
    }


    @Override
    public void sendCode(String phone) {
        HttpMethods.Companion.getInstance().sendCode(phone,
                new HttpObserver(getRootView(), new HttpListener<Object>() {
                    @Override
                    public void onSuccess(@Nullable Object bean) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().sendCodeSuccess();
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                    }
                }, getCompositeDisposable()));
    }

    @Override
    public void telLogin(String phone, String code) {
        HttpMethods.Companion.getInstance().telLogin(phone, code,
                new HttpObserver(getRootView(), new HttpListener<UserBean>() {
                    @Override
                    public void onSuccess(@Nullable UserBean bean) {
                        if (getRootView() == null) {
                            return;
                        }
                        DataManager.Companion.getInstance().saveMyInfo(bean);
                        getRootView().loginSuccess();
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().showErrorDialog(code, msg);
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().showErrorDialog(-1, "");
                    }
                }, getCompositeDisposable()));
    }

    @Override
    public void getWXLoginQRCode() {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                Constants.WeChatAppID, Constants.WeChatAppSecret);
        OkHttpManager.Companion.getInstance().get(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.body() == null) {
                    return;
                }
                String text = response.body().string();
                try {
                    JSONObject object = new JSONObject(text);
                    String access_token = object.optString("access_token");
                    if (TextUtils.isEmpty(access_token)) {
                        return;
                    }
                    getWXTicket(access_token);
                } catch (Exception e) {

                }
            }
        });
    }


    public void getWXTicket(String accessToken) {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=2",
                accessToken);
        OkHttpManager.Companion.getInstance().get(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.body() == null) {
                    return;
                }
                String text = response.body().string();
                try {
                    JSONObject object = new JSONObject(text);
                    String ticket = object.optString("ticket");
                    if (TextUtils.isEmpty(ticket)) {
                        return;
                    }
                    getRootView().getWXTicketSuccess(ticket);
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    public void scanQrCodeLogin(String authCode) {
        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                Constants.WeChatAppID, Constants.WeChatAppSecret, authCode);
        OkHttpManager.Companion.getInstance().get(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.body() == null) {
                    return;
                }
                String text = response.body().string();
                LogUtil.LogE(text);
                try {
                    JSONObject object = new JSONObject(text);
                    String openId = object.optString("openid");
                    String unionId = object.optString("unionid");
                    wxLogin(openId, unionId);
                } catch (Exception e) {

                }
            }
        });
    }

    private void getWXUserInfo(String openId, String accessToken) {
        String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s",
                accessToken, openId);
        OkHttpManager.Companion.getInstance().get(url, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.body() == null) {
                    return;
                }
                String text = response.body().string();
                LogUtil.LogE(text);
            }
        });
    }

    private void wxLogin(String unionid, String openid) {
        HttpMethods.Companion.getInstance().wxLogin(unionid, openid,
                new HttpObserver(getRootView(), new HttpListener<UserBean>() {
                    @Override
                    public void onSuccess(@Nullable UserBean bean) {
                        if (getRootView() == null) {
                            return;
                        }
                        DataManager.Companion.getInstance().saveMyInfo(bean);
                        getRootView().loginSuccess();
                    }

                    @Override
                    public void dataError(@Nullable int code, @Nullable String msg) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().showErrorDialog(code, msg);
                    }

                    @Override
                    public void connectError(@Nullable Throwable e) {
                        if (getRootView() == null) {
                            return;
                        }
                        getRootView().showErrorDialog(-1, "");
                    }
                }, getCompositeDisposable()));
    }
}
